<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElButton, ElInputNumber, ElCheckbox, ElEmpty, ElMessage, ElMessageBox, ElDialog, ElSelect, ElOption } from 'element-plus'
import CommonHeader from '@/components/CommonHeader.vue'
import CommonFooter from '@/components/CommonFooter.vue'
import FloatingSidebar from '@/components/FloatingSidebar.vue'
import { Delete } from '@element-plus/icons-vue'
import { Picture } from '@element-plus/icons-vue'
import { useCartStore } from '@/stores/cart.js'
import { querySpecsByProductId } from '@/api/cart.js'

const router = useRouter()
const cartStore = useCartStore()

// 错误状态
const error = ref(null)

// 规格修改相关状态
const showSpecsDialog = ref(false)
const currentEditingItem = ref(null)
const availableSpecs = ref({})
const selectedSpecs = ref({})
const loadingSpecs = ref(false)

// 管理模式开关
const isManageMode = ref(false)
const toggleManageMode = () => {
  isManageMode.value = !isManageMode.value
}

// 页面加载时获取购物车数据
onMounted(async () => {
  try {
    await cartStore.fetchCartItems()
    // 默认全不选
    cartStore.cartItems.forEach(item => {
      item.selected = false
      item.editQuantity = item.quantity // 新增本地编辑数量
    })
  } catch (err) {
    error.value = '获取购物车数据失败，请稍后重试'
  }
})

// 在组件卸载前确保body的overflow样式被重置
onUnmounted(() => {
  document.body.style.overflow = '';
})

// 计算总价、原价、节省金额、已选数量都用 editQuantity（如果有）
const getItemCalcQuantity = (item) => {
  return typeof item.editQuantity === 'number' ? item.editQuantity : (item.quantity || 0)
}

const totalPrice = computed(() => {
  return cartStore.cartItems
    .filter(item => item.selected)
    .reduce((sum, item) => sum + (item.productCurrentPrice || 0) * getItemCalcQuantity(item), 0)
})

const totalOriginalPrice = computed(() => {
  return cartStore.cartItems
    .filter(item => item.selected)
    .reduce((sum, item) => sum + (item.productPrice || 0) * getItemCalcQuantity(item), 0)
})

const totalSaved = computed(() => {
  return cartStore.cartItems
    .filter(item => item.selected)
    .reduce((sum, item) => sum + ((item.productPrice || 0) - (item.productCurrentPrice || 0)) * getItemCalcQuantity(item), 0)
})

const selectedCount = computed(() => {
  return cartStore.cartItems.filter(item => item.selected).reduce((sum, item) => sum + getItemCalcQuantity(item), 0)
})

// 计算属性：是否全选
const isAllSelected = computed({
  get: () => cartStore.isAllSelected,
  set: (value) => {
    cartStore.isAllSelected = value
  }
})

// 处理商品数量变化（只改本地 editQuantity，不同步数据库）
const handleEditQuantityChange = (item) => {
  if (item.editQuantity < 1) {
    item.editQuantity = 1
  }
  if (item.editQuantity > 99) {
    item.editQuantity = 99
    ElMessage.warning('商品数量不能超过99件')
  }
}

// 保存单个商品数量到数据库
const handleSaveQuantity = async (item) => {
  if (item.editQuantity === item.quantity) return
  try {
    await cartStore.updateQuantityToServer(item.id, item.editQuantity)
    item.quantity = item.editQuantity // 同步本地
    ElMessage.success('数量已保存')
    isManageMode.value = false // 保存后退出管理模式
  } catch (error) {
    ElMessage.error('保存失败，请重试')
    item.editQuantity = item.quantity // 回滚
  }
}

// 批量保存所有有变动的商品
const handleSaveAllQuantities = async () => {
  const changedItems = cartStore.cartItems.filter(item => item.editQuantity !== item.quantity)
  if (changedItems.length === 0) {
    ElMessage.info('没有需要保存的更改')
    return
  }
  let successCount = 0
  for (const item of changedItems) {
    try {
      await cartStore.updateQuantityToServer(item.id, item.editQuantity)
      item.quantity = item.editQuantity
      successCount++
    } catch (error) {
      ElMessage.error(`商品 ${item.productTitle || item.id} 保存失败`)
      item.editQuantity = item.quantity
    }
  }
  if (successCount > 0) {
    ElMessage.success(`成功保存${successCount}个商品的数量`)
  }
}

// 移除购物车商品
const handleRemoveItem = async (cartItemId) => {
  ElMessageBox.confirm('确定要从购物车中移除此商品吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      await cartStore.removeFromCart(cartItemId)
    } catch (error) {
      // 处理错误
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 结算时也用 editQuantity（如果有）
const handleCheckout = async () => {
  // 不再自动保存 editQuantity 到数据库
  const selectedItems = cartStore.getSelectedItems()
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要结算的商品！')
    return
  }
  router.push({
    path: '/home/order/confirm',
    query: {
      items: JSON.stringify(selectedItems.map(item => ({
        id: item.id,
        productId: item.productId,
        name: item.productTitle,
        price: item.productCurrentPrice,
        originalPrice: item.productPrice,
        image: item.productImage,
        quantity: getItemCalcQuantity(item), // 只发本次要买的数量
        specs: item.specs
      })))
    }
  })
}

// 批量删除购物车商品
const handleBatchRemove = () => {
  const selectedItems = cartStore.getSelectedItems()
  if (selectedItems.length === 0) {
    ElMessage.warning('请选择要删除的商品！')
    return
  }
  
  ElMessageBox.confirm(`确定要删除选中的 ${selectedItems.length} 件商品吗？`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      const cartItemIds = selectedItems.map(item => item.id)
      await cartStore.batchRemoveFromCart(cartItemIds)
    } catch (error) {
      // 处理错误
    }
  }).catch(() => {
    // 用户取消删除
  })
}

// 重新加载购物车数据
const retryLoad = async () => {
  error.value = null
  try {
    await cartStore.fetchCartItems()
  } catch (err) {
    error.value = '重新加载失败，请稍后重试'
  }
}

// 跳转到商品详情页
const goToProductDetail = (productId) => {
  document.body.style.overflow = '';
  router.push({
    path: `/home/product/${productId}`
  })
}

// 解析商品规格信息
const getParsedSpecs = (specs) => {
  if (specs && typeof specs === 'string') {
    try {
      return JSON.parse(specs);
    } catch (error) {
      return null;
    }
  }
  return specs;
}

// 获取选中的规格信息
const getSelectedSpecs = (specs) => {
  if (!specs || typeof specs !== 'object') {
    return {};
  }
  
  const selectedSpecs = {};
  Object.keys(specs).forEach(specName => {
    const specValues = specs[specName];
    if (Array.isArray(specValues) && specValues.length > 0) {
      selectedSpecs[specName] = specValues[0];
    }
  });
  
  return selectedSpecs;
}

// 获取购物车商品的选中规格信息
const getCartItemSelectedSpecs = (item) => {
  return getSelectedSpecs(item.specs);
}

// 检查商品是否有选中的规格信息
const hasSelectedSpecs = (item) => {
  const selectedSpecs = getSelectedSpecs(item.specs);
  return selectedSpecs && Object.keys(selectedSpecs).length > 0;
}

// 打开规格修改弹窗
const openSpecsDialog = async (item) => {
  currentEditingItem.value = item;
  loadingSpecs.value = true;
  showSpecsDialog.value = true;
  
  try {
    // 根据商品ID获取完整的规格选项
    const result = await querySpecsByProductId(item.productId);
    const specs = result.data;
    
    if (specs && Object.keys(specs).length > 0) {
      availableSpecs.value = specs;
      
      // 初始化选中的规格，使用当前购物车项的规格值
      selectedSpecs.value = {};
      Object.keys(specs).forEach(specName => {
        const currentValue = item.specs && item.specs[specName] ? item.specs[specName][0] : null;
        if (currentValue && specs[specName].includes(currentValue)) {
          selectedSpecs.value[specName] = currentValue;
        } else if (specs[specName].length > 0) {
          selectedSpecs.value[specName] = specs[specName][0];
        }
      });
    } else {
      availableSpecs.value = {};
      selectedSpecs.value = {};
      ElMessage.warning('该商品暂无规格选项');
    }
  } catch (error) {
    ElMessage.error('获取商品规格失败，请重试');
    availableSpecs.value = {};
    selectedSpecs.value = {};
  } finally {
    loadingSpecs.value = false;
  }
}

// 关闭规格修改弹窗
const closeSpecsDialog = () => {
  showSpecsDialog.value = false;
  currentEditingItem.value = null;
  selectedSpecs.value = {};
  availableSpecs.value = {};
}

// 确认规格修改
const confirmSpecsChange = async () => {
  if (!currentEditingItem.value) return;
  
  try {
    // 构建新的规格数据，确保是正确的对象格式
    const newSpecs = {};
    Object.keys(selectedSpecs.value).forEach(specName => {
      newSpecs[specName] = [selectedSpecs.value[specName]]; // 保持数组格式
    });
    
    // 更新购物车商品的规格
    const updatedItem = {
      ...currentEditingItem.value,
      specs: newSpecs
    };
    
    // 只传递必要的字段给后端，传递对象而不是JSON字符串
    const updateData = {
      id: updatedItem.id,
      specs: newSpecs // 直接传递对象，让JacksonTypeHandler处理
    };
    
    await cartStore.updateCartItemSpecs(updateData);
    
    ElMessage.success('规格修改成功');
    closeSpecsDialog();
  } catch (error) {
    ElMessage.error('规格修改失败，请重试');
  }
}
</script>

<template>
  <CommonHeader />
  <FloatingSidebar />
  <div class="cart-page">
    <div class="container">
      <div class="page-title-bar">
        <h1 class="page-title">我的购物车</h1>
        <el-button type="info" size="small" @click="toggleManageMode" class="manage-btn">
          {{ isManageMode ? '完成' : '管理' }}
        </el-button>
      </div>

      <div v-if="cartStore.loading" class="loading-container">
        <div class="loading-spinner"></div>
        <p>正在加载购物车数据...</p>
      </div>

      <div v-else-if="error" class="error-container">
        <el-empty description="加载失败" :image-size="100">
          <p class="error-message">{{ error }}</p>
          <el-button type="primary" @click="retryLoad">重新加载</el-button>
        </el-empty>
      </div>

      <div v-else-if="cartStore.cartItems.length > 0" class="cart-content">
        <div class="cart-items-list">
          <el-card class="cart-item-card" v-for="item in cartStore.cartItems" :key="item.id">
            <div class="item-header">
              <el-checkbox v-model="item.selected"></el-checkbox>
              <el-image 
                :src="item.productImage" 
                fit="cover" 
                class="item-image" 
                :preview-src-list="[item.productImage]"
                :error="() => true"
                @click="goToProductDetail(item.productId)"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>图片加载失败</span>
                  </div>
                </template>
              </el-image>
              <div class="item-details">
                <h3 class="item-name">{{ item.productTitle || '商品名称未知' }}</h3>
                
                <!-- 商品规格信息 -->
                <div v-if="hasSelectedSpecs(item) && Object.keys(getCartItemSelectedSpecs(item)).length > 0" class="item-specs">
                  <span 
                    v-for="(value, specName) in getCartItemSelectedSpecs(item)" 
                    :key="specName" 
                    class="spec-item"
                  >
                    <span class="spec-label">{{ specName }}:</span>
                    <span class="spec-value">{{ value }}</span>
                  </span>
                  <el-button 
                    type="text" 
                    size="small" 
                    @click="openSpecsDialog(item)"
                    class="edit-specs-btn"
                  >
                    修改规格
                  </el-button>
                </div>
                
                <div class="item-price">
                  <span class="current-price">¥{{ (item.productCurrentPrice || 0).toFixed(2) }}</span>
                  <span v-if="item.productPrice && item.productPrice > item.productCurrentPrice" class="original-price">¥{{ (item.productPrice || 0).toFixed(2) }}</span>
                </div>
                <div class="item-subtotal" v-if="(item.quantity || 0) > 1">
                  小计: ¥{{ ((item.productCurrentPrice || 0) * (item.quantity || 0)).toFixed(2) }}
                  <span v-if="item.productPrice && item.productPrice > item.productCurrentPrice" class="saved-amount">
                    节省: ¥{{ (((item.productPrice || 0) - (item.productCurrentPrice || 0)) * (item.quantity || 0)).toFixed(2) }}
                  </span>
                </div>
              </div>
              <div class="item-actions">
                <el-input-number 
                  v-model="item.editQuantity"
                  :min="1"
                  :max="99"
                  :step="1"
                  :precision="0"
                  @change="handleEditQuantityChange(item)"
                  size="small"
                  controls-position="both"
                />
                <el-button 
                  v-if="isManageMode"
                  type="primary" 
                  size="small" 
                  @click="handleSaveQuantity(item)"
                  :disabled="item.editQuantity === item.quantity"
                  style="margin-left: 8px;"
                >
                  保存
                </el-button>
                <el-button type="danger" :icon="Delete" circle @click="handleRemoveItem(item.id)"></el-button>
              </div>
            </div>
          </el-card>
        </div>

        <!-- 购物车底部结算区域 -->
        <div class="cart-footer-summary">
          <div class="select-all">
            <el-checkbox v-model="isAllSelected">全选</el-checkbox>
            <span class="selected-count">已选择 {{ selectedCount }} 件商品</span>
            <el-button 
              v-if="selectedCount > 0" 
              type="danger" 
              size="small" 
              @click="handleBatchRemove"
              style="margin-left: 10px;"
            >
              删除选中
            </el-button>
          </div>
          <div class="total-info">
            <div class="total-price">
              总计: <span class="price-value">¥{{ (totalPrice || 0).toFixed(2) }}</span>
              <span v-if="totalOriginalPrice > totalPrice" class="original-total">¥{{ (totalOriginalPrice || 0).toFixed(2) }}</span>
            </div>
            <div v-if="totalSaved > 0" class="total-saved">
              节省: <span class="saved-value">¥{{ (totalSaved || 0).toFixed(2) }}</span>
            </div>
            <div class="total-desc">不含运费</div>
          </div>
          <el-button 
            v-if="isManageMode"
            type="success" 
            size="small" 
            @click="handleSaveAllQuantities"
            style="margin-left: 10px;"
          >
            全部保存
          </el-button>
          <el-button type="primary" size="large" @click="handleCheckout" :disabled="selectedCount === 0">
            去结算 ({{ selectedCount }})
          </el-button>
        </div>
      </div>

      <el-empty v-else description="购物车还是空的，快去购物吧！">
        <el-button type="primary" @click="router.push('/home')">去首页</el-button>
      </el-empty>
    </div>
  </div>
  <CommonFooter />
  
  <!-- 规格修改弹窗 -->
  <el-dialog 
    v-model="showSpecsDialog" 
    title="修改商品规格" 
    width="500px"
    :before-close="closeSpecsDialog"
  >
    <div v-if="currentEditingItem" class="specs-dialog-content">
      <div class="product-info">
        <el-image 
          :src="currentEditingItem.productImage" 
          fit="cover" 
          class="product-image"
          style="width: 80px; height: 80px; border-radius: 4px;"
        />
        <div class="product-details">
          <h4>{{ currentEditingItem.productTitle }}</h4>
          <p class="product-price">¥{{ (currentEditingItem.productCurrentPrice || 0).toFixed(2) }}</p>
        </div>
      </div>
      
      <div class="specs-selection">
        <h5>选择规格：</h5>
        
        <!-- 加载状态 -->
        <div v-if="loadingSpecs" class="loading-specs">
          <div class="loading-spinner"></div>
          <p>正在加载规格选项...</p>
        </div>
        
        <!-- 规格选项 -->
        <div v-else-if="Object.keys(availableSpecs).length > 0">
          <div 
            v-for="(options, specName) in availableSpecs" 
            :key="specName" 
            class="spec-group"
          >
            <label class="spec-label">{{ specName }}：</label>
            <el-select 
              v-model="selectedSpecs[specName]"
              placeholder="请选择"
              size="small"
              style="min-width: 120px"
            >
              <el-option
                v-for="option in options"
                :key="option"
                :label="option"
                :value="option"
              />
            </el-select>
          </div>
        </div>
        
        <!-- 无规格选项 -->
        <div v-else class="no-specs">
          <p>该商品暂无规格选项</p>
        </div>
      </div>
    </div>
    
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeSpecsDialog">取消</el-button>
        <el-button 
          type="primary" 
          @click="confirmSpecsChange"
          :disabled="loadingSpecs || Object.keys(availableSpecs).length === 0"
        >
          确认修改
        </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped>
/* 购物车页面样式 */
.cart-page {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.page-title-bar {
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  margin-bottom: 20px;
}

.page-title {
  font-size: 28px;
  color: #303133;
  margin-bottom: 0;
  text-align: center;
}

.manage-btn {
  position: absolute;
  right: 0;
  top: 50%;
  transform: translateY(-50%);
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: #909399;
}

.loading-container p {
  margin-top: 10px;
  font-size: 14px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #409eff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.error-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 50px 0;
  color: #909399;
}

.error-message {
  margin: 10px 0;
  color: #f56c6c;
  font-size: 14px;
}

.cart-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.cart-items-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.cart-item-card {
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.cart-item-card:hover {
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.item-header {
  display: flex;
  align-items: center;
  padding: 15px;
}

.item-image {
  width: 100px;
  height: 100px;
  border-radius: 4px;
  margin-right: 20px;
  object-fit: cover;
  cursor: pointer;
}

.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100px;
  height: 100px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #909399;
  font-size: 12px;
}

.image-error .el-icon {
  font-size: 24px;
  margin-bottom: 4px;
}

.item-details {
  flex-grow: 1;
}

.item-name {
  font-size: 16px;
  color: #303133;
  margin: 0 0 8px 0;
}

.item-specs {
  margin-bottom: 8px;
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.spec-item {
  display: inline-flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 12px;
  border: 1px solid #e4e7ed;
}

.spec-label {
  font-weight: 500;
  color: #606266;
  margin-right: 4px;
}

.spec-value {
  color: #303133;
  font-weight: 400;
}

.item-price {
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.current-price {
  color: #f56c6c;
  font-weight: bold;
}

.original-price {
  color: #909399;
  text-decoration: line-through;
  font-size: 14px;
  font-weight: normal;
}

.item-subtotal {
  font-size: 14px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 8px;
}

.saved-amount {
  color: #f56c6c;
  font-weight: bold;
}

.item-actions {
  display: flex;
  align-items: center;
  gap: 15px;
}

.cart-footer-summary {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
  background-color: #fcfcfc;
  border-radius: 8px;
}

.select-all {
  display: flex;
  align-items: center;
  gap: 10px;
}

.selected-count {
  color: #909399;
  font-size: 14px;
}

.total-info {
  text-align: right;
}

.total-price {
  font-size: 20px;
  color: #303133;
  margin-bottom: 4px;
}

.price-value {
  color: #f56c6c;
  font-weight: bold;
}

.original-total {
  font-size: 14px;
  color: #909399;
  margin-left: 10px;
}

.total-saved {
  font-size: 14px;
  color: #f56c6c;
  margin-top: 4px;
}

.saved-value {
  color: #f56c6c;
  font-weight: bold;
}

.total-desc {
  font-size: 12px;
  color: #909399;
}

.el-empty {
  padding: 50px 0;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .item-header {
    flex-wrap: wrap;
  }
  
  .item-image {
    width: 80px;
    height: 80px;
  }
  
  .item-actions {
    width: 100%;
    margin-top: 10px;
    justify-content: flex-end;
  }
  
  .cart-footer-summary {
    flex-direction: column;
    gap: 15px;
  }
  
  .total-info {
    text-align: center;
  }
}

.edit-specs-btn {
  margin-left: 8px;
  color: #409eff;
  font-size: 12px;
  padding: 0;
  height: auto;
}

.edit-specs-btn:hover {
  color: #66b1ff;
}

/* 规格修改弹窗样式 */
.specs-dialog-content {
  padding: 20px 0;
}

.product-info {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.product-details {
  margin-left: 15px;
}

.product-details h4 {
  margin: 0 0 8px 0;
  font-size: 16px;
  color: #303133;
}

.product-price {
  margin: 0;
  font-size: 18px;
  color: #f56c6c;
  font-weight: bold;
}

.specs-selection h5 {
  margin: 0 0 15px 0;
  font-size: 14px;
  color: #606266;
}

.spec-group {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.spec-group .spec-label {
  width: 80px;
  font-size: 14px;
  color: #606266;
  margin-right: 10px;
}

.spec-group .el-select {
  flex: 1;
  max-width: 200px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.loading-specs {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  color: #909399;
}

.loading-specs p {
  margin-top: 10px;
  font-size: 14px;
}

.no-specs {
  text-align: center;
  padding: 20px;
  color: #909399;
}

/* 放大选择框并美化 */
.item-header .el-checkbox .el-checkbox__inner {
  width: 22px;
  height: 22px;
  border-radius: 8px;
  border: 2px solid #409eff;
}

.item-header .el-checkbox.is-checked .el-checkbox__inner {
  background-color: #409eff;
  border-color: #409eff;
}

.item-header .el-checkbox.is-checked .el-checkbox__inner::after {
  border-width: 3px;
  left: 6px;
  top: 1px;
  width: 6px;
  height: 12px;
}

/* 拉开与图片的距离 */
.item-header .el-checkbox {
  margin-right: 18px;
}
</style> 